<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { handleTree } from '@vben/utils';
import { Tree } from 'ant-design-vue';
import {
    getTree,
    getbByByGroup,
    getSyncState,
    getAllCamera,
} from '#/api/moxi/bxccameragroup';
import { Card, Descriptions, DescriptionsItem, message } from 'ant-design-vue';

const emit = defineEmits(['select']);
const loading = ref(false); // 加载状态
const deptList = ref<any[]>([]); // 部门列表
const deptTree = ref<any[]>([]); // 部门树
const department = ref(); // 加载状态

/** 初始化 */
onMounted(async () => {
    try {
        loading.value = true;
        const treeData = await getTree();
        console.log('获取摄像头分组树状图数据', treeData);
        deptList.value = treeData;
        deptTree.value = handleTree(treeData);
    } catch (error) {
        console.error('获取部门数据失败', error);
    } finally {
        loading.value = false;
    }
});

const handleSelect = (_selectedKeys: any[], info: any) => {
    console.log('选中部门', info.node.dataRef);
    console.log('选中部门', info.node.dataRef.name);
    department.value = info.node.dataRef.name;
    getAll(info.node.dataRef.id);
    fetchCameraStat(info.node.dataRef.id);
};

// 锚点位置和参数
// const cameraPoints = [
//     { cx: 31, cy: 31 },
//     { cx: 38, cy: 30.5 },
//     { cx: 46.5, cy: 30 },
//     // 可以继续添加更多摄像头坐标
// ];
const cameraPoints = [
    { id: 1, leftPercent: 15, topPercent: 7.5 },
    { id: 2, leftPercent: 24, topPercent: 6.5 },
    { id: 3, leftPercent: 34.5, topPercent: 6 },
]
// 查询分组下所有摄像头
const getAll = async (id: number) => {
    try {
        const params = {
            groupId: id,
            pageNo: 1,
            pageSize: 100,
        };
        const res = await getAllCamera(params);
        // 合并锚点和摄像头数据
        if (res.list && res.list.length > 0) {
            res.list.forEach((camera: any, index: number) => {
                if (index < cameraPoints.length) {
                    // 将 API 返回的摄像头数据合并到对应索引的 cameraPoints 中
                    Object.assign(cameraPoints[index], camera);
                }
            });
        }
        console.log('查询分组下所有摄像头', cameraPoints);
    } catch (error) {
        console.error('获取分组详情失败', error);
    }
};
const visitorObject = ref({
    all: '--', //总数
    allOnline: '--', //总在线数量
    allOffline: '--', //总离线数量
    group: '--', //分组下总数量
    groupOnline: '--', //分组下在线数量
    groupOffline: '--', //分组下离线数量
});
// 获取摄像头数量统计
const fetchCameraStat = async (id: number) => {
    try {
        const params = {
            groupId: id,
        };
        const res = await getbByByGroup(params);
        console.log('分组详情', res);
        visitorObject.value = res;
        // 这里可以处理返回的数据，比如存到某个变量
    } catch (error) {
        console.error('获取分组详情失败', error);
    }
};

// 定义弹窗
const open = ref<boolean>(false);
const selectedCamera = ref<any>({
    nickname: '',
    id: '',
    playUrl: null,
    forwardState: '',
});
// 锚点点击事件
const handleCameraClick = (val: any) => {
    console.log('点击了摄像头', val);
    if (val) {
        selectedCamera.value = val;
    }
    open.value = true; //打开弹窗
};
const getStatusColor = (status: string) => {
    return status == '1' ? 'text-green-500' : status == '1' ? 'text-red-500' : '';
};
const videoRef = ref<HTMLVideoElement | null>(null);
// 关闭抽屉结束视频
const handleDrawerClose = () => {
    if (videoRef.value) {
        videoRef.value.pause();
        videoRef.value.currentTime = 0; // 可选：重置播放进度
    }
};
const syncLoading = ref(false);
const loadingDisabled = ref(false);
// 同步数据
const syncBtn = async () => {
    try {
        syncLoading.value = true;
        loadingDisabled.value = true;
        const res = await getSyncState();
        if (res) {
            message.success('同步数据成功');
        }
        console.log('同步数据', res);
        // 这里可以处理返回的数据，比如存到某个变量
    } catch (error) {
        console.error('获取分组详情失败', error);
    } finally {
        syncLoading.value = false;
        loadingDisabled.value = false;
    }
};
</script>

<template>
    <Page auto-content-height>
        <div class="flex h-full w-full p-4">
            <!-- 左侧部门树 -->
            <Card class="mr-4 h-full w-1/6">
                <Tree style="margin-top: 20px" :spinning="loading" class="h-full pt-2" v-if="deptTree.length > 0"
                    :tree-data="deptTree" :field-names="{ title: 'name', key: 'id', children: 'children' }"
                    @select="handleSelect" :default-expand-all="true" />
            </Card>
            <!-- 右侧用户列表 -->
            <!-- bg-card -->
            <div class="flex h-full w-5/6 flex-col rounded-md bg-gray-100" :spinning="syncLoading">
                <div class="bg-card flex h-[86px] items-center justify-end rounded-lg p-2">
                    <a-button type="primary" @click="syncBtn" :disabled="loadingDisabled">同步数据</a-button>
                </div>
                <div class="bg-card mt-3 flex-1 rounded-lg p-10">
                    <div class="mb-4">
                        <div class="mb-6 grid grid-cols-6 gap-4">
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">总摄像头数量</div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.all }}
                                </div>
                            </div>
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">总在线数量</div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.allOnline }}
                                </div>
                            </div>
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">总离线摄像头</div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.allOffline }}
                                </div>
                            </div>
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">
                                    分组下的总摄像头数量
                                </div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.group }}
                                </div>
                            </div>
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">分组下的总在线数量</div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.groupOnline }}
                                </div>
                            </div>
                            <div class="rounded-lg bg-white p-4 text-center">
                                <div class="mt-1 text-sm text-gray-500">
                                    分组下的总离线头数量
                                </div>
                                <div class="text-2xl font-bold text-blue-600">
                                    {{ visitorObject.groupOffline }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-5" v-if="department">
                        <div class="relative inline-block w-full">
                            <img 
                                src="./img/w1.jpg" 
                                alt="摄像头平面图" 
                                class="h-auto w-full rounded-lg" 
                            />
                            <!-- 使用绝对定位的锚点 -->
                            <div 
                                v-for="point in cameraPoints" 
                                :key="point.id"
                                class="absolute cursor-pointer transform -translate-x-1/2 -translate-y-1/2 transition-all hover:scale-150"
                                :style="{
                                    left: point.leftPercent + '%',
                                    top: point.topPercent + '%'
                                }"
                                @click="handleCameraClick(point)"
                            >
                                <div class="w-7 h-7 bg-red-500 rounded-full border-2 border-red-600 shadow-lg opacity-50 hover:opacity-60"></div>
                            </div>
                        </div>
                    </div>

                    <div class="mt-5 flex h-64 items-center justify-center rounded-lg" v-else>
                        <div class="text-center text-gray-500">
                            <p class="text-lg font-medium">暂无数据</p>
                            <p class="text-lg font-medium">请选择有摄像头的部门</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <a-drawer v-model:open="open" class="custom-class" size="large" :closable="false"
            root-class-name="root-class-name" :root-style="{ color: 'blue' }" style="color: red" title="摄像头详情"
            placement="right" @close="handleDrawerClose">
            <Card :bordered="false" class="md:w-2/2 w-full">
                <div class="mb-2 flex items-center rounded-lg p-3">
                    <div>
                        <IconifyIcon class="m-2 text-2xl" icon="lucide:book-marked" />
                    </div>
                    <span class="mr-2 text-xl font-medium">摄像头信息</span>
                </div>
                <Descriptions :column="2" bordered :label-style="{ width: '138px' }">
                    <DescriptionsItem label="摄像头名称" :span="2">{{
                        selectedCamera.nickname || '--'
                        }}</DescriptionsItem>
                    <DescriptionsItem label="摄像头id" :span="2">{{
                        selectedCamera.id || '--'
                        }}</DescriptionsItem>
                    <DescriptionsItem label="摄像头状态" :span="2">
                        <span :class="getStatusColor(selectedCamera.forwardState)">{{
                            selectedCamera.forwardState == 1
                                ? '转发中'
                                : selectedCamera.forwardState == 0
                            ? '未转发'
                            : '--'
                            }}</span>
                    </DescriptionsItem>
                </Descriptions>

                <div class="mb-2 mt-4 flex items-center rounded-lg p-3">
                    <span class="mr-4 text-xl font-medium">视频信息</span>
                </div>
                <!-- {{ selectedCamera.playUrl }} -->
                <video width="640" ref="videoRef" height="360" controls :src="selectedCamera.playUrl"></video>
            </Card>
        </a-drawer>
    </Page>
</template>
